package zhao.ben.quan.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import zhao.ben.quan.dao.PermissionDao;
import zhao.ben.quan.dao.RoleDao;
import zhao.ben.quan.dao.UserDao;
import zhao.ben.quan.pojo.Permission;
import zhao.ben.quan.pojo.Role;
import zhao.ben.quan.pojo.User;
import zhao.ben.quan.service.UserService;

import java.util.Set;

/**
 * 用户的服务业务层
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    //根据用户名查询数据库获取用户信息和关联的角色信息,同时需要查询角色关联的权限信息
    public User findByUsername(String name) {
        User user = userDao.findByName(name);

        if(user==null){
            return null;
        }

        //根据用户id查询对应的角色
        Set<Role> roles = roleDao.findByUserId(user.getId());
        user.setRoles(roles);//让用户关联角色

        for (Role role : roles) {
            //根据角色id查询关联的权限
            Set<Permission> permissions = permissionDao.findByRoleId(role.getId());
            role.setPermissions(permissions);//让角色关联权限
        }
        return user;
    }
}
